import { Form, Modal, Table } from 'antd';
import React from 'react';
import { FormComponentProps } from 'antd/es/form';
import { ColumnProps, TableRowSelection } from 'antd/lib/table';
import { Product } from '@/models/product';
import { NewProductRecommend } from '../model';

const columns: ColumnProps<Product>[] = [
  {
    title: '商品名称',
    dataIndex: 'name',
    align: 'center',
  },
  {
    title: '货号',
    dataIndex: 'productSn',
    align: 'center',
    render: text => `NO.${text}`,
  },
  {
    title: '价格',
    dataIndex: 'price',
    align: 'center',
    render: text => `￥${text}`,
  },
];

interface CollectionCreateFormProps extends FormComponentProps {
  products: Product[];
  recommends: NewProductRecommend[];
  visible?: boolean;
  onCancel?: (e: React.MouseEvent<HTMLElement>) => void;
  onCreate?: (selectedRows: any) => void;
  onTableLoading?: boolean;
  onConfirmLoading?: boolean;
}

const CollectionCreateForm = Form.create<CollectionCreateFormProps>({ name: 'form_in_modal' })(
  class extends React.Component<CollectionCreateFormProps> {
    selectedRows: Product[] = [];

    rowSelection: TableRowSelection<Product> = {
      onChange: (_selectedRowKeys, selectedRows) => {
        this.selectedRows = selectedRows.map(each => ({
          ...each,
          productId: each.id,
          productName: each.name,
        }));
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name,
      }),
    };

    render() {
      const {
        visible,
        onCancel,
        onCreate,
        onTableLoading,
        onConfirmLoading,
        products,
        recommends,
      } = this.props;
      const recommendIds = (recommends || []).map(each => each.productId);
      const dataSource = (products || []).filter(each => recommendIds.indexOf(each.id!) === -1);
      return (
        <Modal
          width={700}
          visible={visible}
          title="选择商品"
          okText="推荐"
          cancelText="取消"
          onCancel={onCancel}
          onOk={() => {
            onCreate!(this.selectedRows);
          }}
          confirmLoading={onConfirmLoading}
        >
          <Table<Product>
            dataSource={dataSource}
            columns={columns}
            rowSelection={this.rowSelection}
            rowKey="id"
            bordered
            loading={onTableLoading}
          />
        </Modal>
      );
    }
  },
);

export default CollectionCreateForm;
